# coding: utf-8
# @Author: cyl
# @File: 03json.py
# @Time: 2024/07/28 20:53:01
import json


# dumps 反序列化 -> 将python对象转换为字符串
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
data2 = json.dumps(data)
print(data2)
print(type(data2))

data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
data2 = json.dumps({'a': 'Runoob', 'b': 7}, sort_keys=True, indent=4, separators=(',', ': '))
print(data2)   # <class 'str'>

# loads 序列化 -> 将字符串转换为python对象
jsonData = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
text = json.loads(jsonData)
print(text)
print(type(text))   # <class 'dict'>
print(text.get("a"))   # 1


# 重要程度: 五颗星(最高)
# 以后会经常操作json, 做接口测试或数据测试, 拿到后端的返回值99%都是json类型的
"""
作业2: 有下面一个类, 其中有三个参数a b c, 需要将abc三个变量及其值转换为json格式并写入当前目录的abc.json下
class Abc:
    a = 1.00012
    b = "222"
    c = "我爱学习"
"""

# json有性能问题, 有更快的库, ujson : `pip install ujson`
# ujson有着和json一样的功能, 但是性能更好
import ujson
import time


def cost_time(func):
    def inner(*args, **kwargs):
        s = time.time()
        result = func(*args, **kwargs)
        e = time.time()
        return result
    return inner

a = {}
for i in range(1, 10000000):
    a[i] = "test_string"

@cost_time
def json_dumps(obj):
    return json.dumps(obj)

@cost_time
def ujson_dumps(obj):
    return ujson.dumps(obj)

ret1 = json_dumps(a)
ret2 = ujson_dumps(a)
print("ret1: ", ret1)   # 5.104785203933716
print("ret2: ", ret2)   # 1.804785203933716
